<template>
  <div>
    <!--搜索框-->
    <div class="research">
      <el-input
        placeholder="通过标题搜索该分类下的博客..."
        v-model="input"
        clearable
        prefix-icon="el-icon-search">
      </el-input>
      <el-button type="primary" icon="el-icon-search" @click="handleResearch">搜索</el-button>
    </div>

    <!--表格-->
    <el-table
      ref="articleTable"
      :data="articleData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55" v-if="showEdit || showDelete">
      </el-table-column>
      <el-table-column
        label="标题"
        width="400"
        show-overflow-tooltip>
        <template slot-scope="scope"><span @click="openView(scope.row)" class="titleLink">{{ scope.row.title }}</span></template>
      </el-table-column>
      <el-table-column
        label="最近编辑时间"
        width="200">
        <template slot-scope="scope">{{ $moment(scope.row.edit_date).format('YYYY-MM-DD HH:mm:ss') }}</template>
      </el-table-column>
      <el-table-column
        prop="author.nickname"
        label="作者"
        width="150"
        show-overflow-tooltip>
      </el-table-column>
      <el-table-column
        prop="category.name"
        label="所属分类"
        width="150"
        show-overflow-tooltip>
      </el-table-column>
      <el-table-column
        label="操作" v-if="showEdit || showDelete">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)" v-if="showEdit">编辑</el-button>
          <el-button
            size="mini"
            @click="handleRestore(scope.$index, scope.row)" v-if="showRestore">还原</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)" v-if="showDelete">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="state"
        label="状态"
        v-else>
      </el-table-column>
    </el-table>

    <!--分页显示栏-->
    <div class="pagination" >
      <el-button type="danger" @click="handleAllDelete" v-if="showEdit || showDelete">批量删除</el-button>
      <!--此处增加一个span，即使上面的按钮不显示了，依然能让分页显示在右边，span充当一个组件-->
      <span></span>
      <el-pagination
        @current-change="handleCurrentChange"
        hide-on-single-page
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total,prev, pager, next, jumper"
        :total="totalResult">
      </el-pagination>
    </div>

    <!--编辑对话框-->
    <el-dialog title="编辑" :visible.sync="dialogFormVisible" :append-to-body=true>
      <el-form :model="form">
        <el-form-item label="标题" label-width="100px">
          <el-input v-model="form.title" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="所属分类" label-width="100px">
          <el-select v-model="form.category" placeholder="请选择所属分类">
            <el-option
              v-for="item in allCategories"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCommit">确 定</el-button>
      </div>
    </el-dialog>

    <!--浏览文章内容对话框-->
    <el-dialog title="文章内容" :visible.sync="dialogTextAreaVisible" :append-to-body=true>
      <!--<el-input-->
        <!--readonly-->
        <!--type="textarea"-->
        <!--:autosize="{ minRows: 2, maxRows: 4}"-->
        <!--placeholder="请输入内容"-->
        <!--v-model="textarea">-->
      <!--</el-input>-->
      <mavonEditor
        style="height: 300px;"
        v-model="textarea"
        :subfield = "prop.subfield"
        :defaultOpen = "prop.defaultOpen"
        :toolbarsFlag = "prop.toolbarsFlag"
        :editable="prop.editable"
        :scrollStyle="prop.scrollStyle"
        :boxShadow="prop.boxShadow"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCommit1">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { mavonEditor } from 'mavon-editor'
    export default {
        name: "ArticleTable",
      components: {
        mavonEditor
      },
      data(){
        return{
          input:'',
          articleData: [],
          currentPage:1,
          pageSize:8,
          totalResult:0,
          multipleSelection: [],
          textarea:'',
          dialogFormVisible: false,//编辑对话框可见性
          dialogTextAreaVisible:false,
          allCategories:[],
          form: {
            id:'',
            title: '',
            category: '',
          },
          temp:[],
        }
      },
      methods:{
        showResult(resp){
          if(resp.data.status==200){
            this.$message({
              type: 'success',
              message: resp.data.info
            });
            this.loadArticle(this.state);
          }else{
            this.$message({
              type: 'error',
              message: resp.data.info
            });
          }
        },
        loadArticle(state){
          const _this = this
          if(state==0){
            this.axios({
              method:'post',
              url:"http://localhost:8081/getAllArticleCount",
            }).then(function (resp) {
              _this.totalResult=resp.data;
            });
            this.axios({
              method:'post',
              url:"http://localhost:8081/getAllArticle",
              params:{'page':_this.currentPage-1,'num':_this.pageSize}
            }).then(function (resp) {
              _this.articleData=resp.data;
            });
          }else{
            var s = '';
            //Switch case 使用严格比较（===）。值必须与要匹配的类型相同。只有操作数属于同一类型时，严格比较才能为 true。
            switch (state) {
              case '1':
                s = "发表";
                break;
              case '2':
                s = "草稿";
                break;
              case '3':
                s = "回收";
                break;
            };
            this.axios({
              method:'post',
              url:"http://localhost:8081/getStateArticleCount",
              params:{'state':s}
            }).then(function (resp) {
              _this.totalResult=resp.data;
            });
            this.axios({
              method:'post',
              url:"http://localhost:8081/getAllArticleByState",
              params:{'page':_this.currentPage-1,'num':_this.pageSize,'state':s}
            }).then(function (resp) {
              _this.articleData=resp.data;
            });
          }
        },
        openView(row){
          this.textarea = row.content;
          this.dialogTextAreaVisible = true;
        },
        handleCommit1(){
          this.dialogTextAreaVisible = false;
        },
        handleResearch(){
          if(this.input==''){
            this.$message({
              type: 'warning',
              message: '请输入文章标题！'
            });
          }else{
            const _this = this;
            if(this.state==0){
              this.axios({
                method:'post',
                url:"http://localhost:8081/getArticleByTitle",
                params:{'title':_this.input}
              }).then(function (resp) {
                _this.totalResult=resp.data.length;
                _this.articleData=resp.data;
              });
            }else{
              var s = '';
              switch (this.state) {
                case '1':
                  s = "发表";
                  break;
                case '2':
                  s = "草稿";
                  break;
                case '3':
                  s = "回收";
                  break;
              };
              this.axios({
                method:'post',
                url:"http://localhost:8081/getArticleByTS",
                params:{'title':_this.input,'state':s}
              }).then(function (resp) {
                _this.totalResult=resp.data.length;
                _this.articleData=resp.data;
              });
            }
          }
        },
        handleSelectionChange(val) {//获取已选择的选项到multipleSelection中
          this.multipleSelection = val;
        },
        handleEdit(index, row) {//处理编辑事件
          if(this.state=='2'){
            this.$router.push({path: '/articlePublish', query: {id:row.id,title:row.title,categoryId:row.category.id,content:row.content}});
          }else{
            this.form.id=row.id;
            this.form.title=row.title;
            this.form.category=row.category.id;
            this.temp.push(this.form.title,this.form.category);
            this.dialogFormVisible=true;
          }
        },
        handleRestore(index, row) {//处理删除事件
          const _this = this;
          this.$confirm('确定将该文章还原?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.axios({
              method:'post',
              url:"http://localhost:8081/updateStateById",
              params:{'id':row.id,'state':'发表'}
            }).then(function (resp) {
              _this.showResult(resp);
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消还原'
            });
          });

        },
        handleDelete(index, row) {//处理删除事件
          var mes='确定将该文章放入回收站?';
          if(this.state==3){
            mes='确定将该文章永久删除?'
          };
          const _this = this;
          this.$confirm(mes, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if(this.state==3){
              this.axios({
                method:'post',
                url:"http://localhost:8081/deleteArticleById",
                params:{'id':row.id}
              }).then(function (resp) {
                _this.showResult(resp);
              });
            }else{
              this.axios({
                method:'post',
                url:"http://localhost:8081/updateStateById",
                params:{'id':row.id,'state':'回收'}
              }).then(function (resp) {
                _this.showResult(resp);
              });
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        },
        handleAllDelete(){
          var mes='确定将选中的文章全部放入回收站?';
          if(this.state==3){
            mes='确定将选中的文章全部永久删除?'
          };
          const _this = this;
          if(this.multipleSelection.length==0){
            this.$message({
              message: '请选择要删除的文章',
              type: 'warning'
            });
          } else{
            this.$confirm(mes, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              var id = [];
              for(var i=0;i<this.multipleSelection.length;i++){
                id.push(this.multipleSelection[i].id);
              }
              if(this.state==3){
                this.axios({
                  method:'post',
                  url:"http://localhost:8081/deleteArticleById",
                  params:{'id':id.toString()}
                }).then(function (resp) {
                  _this.showResult(resp);
                });
              }else{
                this.axios({
                  method:'post',
                  url:"http://localhost:8081/updateStateById",
                  params:{'id':id.toString(),'state':'回收'}
                }).then(function (resp) {
                  _this.showResult(resp);
                });
              }
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });
            });
          }
        },
        handleCurrentChange(val) {
          this.loadArticle(this.state);
        },
        handleCommit(){
          var i = [];
          i.push(this.form.title,this.form.category);
          if(!this.$utils.judgeResultFun(this.temp,i)){
            const _this = this;
            this.axios({
              method:'post',
              url:"http://localhost:8081/updateTCById",
              params:{'id':this.form.id,'title':this.form.title,'cid':this.form.category}
            }).then(function (resp) {
              _this.showResult(resp);
            });
            this.dialogFormVisible = false;
          }else{
            this.dialogFormVisible = false;
          }
          this.temp = [];
        }
      },
      mounted(){
        this.loadArticle(this.state);
        const _this = this;
        this.axios({
          method:'post',
          url:"http://localhost:8081/getAllCategory",
        }).then(function (resp) {
          _this.allCategories=resp.data;
        });
      },
      computed: {
        prop () {
          let data = {
            subfield: false,// 单双栏模式
            defaultOpen: 'preview',//edit： 默认展示编辑区域 ， preview： 默认展示预览区域
            editable: false,
            toolbarsFlag: false,
            scrollStyle: false,
            boxShadow:false//边框
          }
          return data
        }
      },
      props: ['state', 'showEdit', 'showDelete', 'activeName', 'showRestore']
    }
</script>

<style>
  .titleLink{
    /*text-decoration: none;*/
    color: #409EFF;
    cursor: pointer;
  }

  .pagination{
    margin-top: 10px;
    /*display: flex;
    justify-content: space-between;配合使用，用空格自动填补中间区域，让组件左右对齐*/
    display: flex;
    justify-content: space-between;
  }

  .pagination .el-button{
    height: 30px;
    padding: 0px 15px;
  }

  /*搜索框样式*/
  .research{
    display: flow;
    width: 500px;
  }

  .research .el-input__inner{
    height: 30px;
    line-height: 30px;
  }

  .research .el-input__icon{
    line-height: 30px;
  }

  .research .el-input{
    width: 80%;
  }

  .research .el-button{
    height: 30px;
    padding: 0px 15px;
  }
</style>
